package com.examstack.portal.controller.page;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.examstack.common.domain.exam.UserQuestionCollect;
import com.examstack.common.domain.exam.UserQuestionHistory;
import com.examstack.common.domain.news.News;
import com.examstack.common.domain.practice.KnowledgePointAnalysisResult;
import com.examstack.common.domain.practice.TypeAnalysis;
import com.examstack.common.domain.question.Field;
import com.examstack.common.domain.question.KnowledgePoint;
import com.examstack.common.domain.question.QuestionQueryResult;
import com.examstack.common.domain.question.QuestionStatistic;
import com.examstack.common.domain.question.QuestionType;
import com.examstack.common.util.Page;
import com.examstack.common.util.QuestionAdapter;
import com.examstack.portal.persistence.QuestionHistoryMapper;
import com.examstack.portal.persistence.QuestionMapper;
import com.examstack.portal.security.UserInfo;
import com.examstack.portal.service.NewsService;
import com.examstack.portal.service.QuestionCollectService;
import com.examstack.portal.service.QuestionHistoryService;
import com.examstack.portal.service.QuestionService;

@Controller
public class PracticePage {

	@Autowired
	private NewsService newsService;
	@Autowired
	private QuestionService questionService;
	@Autowired
	private QuestionHistoryService questionHistoryService;
	@Autowired
	private QuestionCollectService questionCollectService;
	@Autowired
	private QuestionHistoryMapper questionHistoryMapper;
	@Autowired
	private QuestionMapper questionMapper;

	/**
	 * 强化练习
	 * 
	 * @param model
	 * @param request
	 * @param knowledgePointId
	 * @param questionTypeId
	 * @return
	 */
	@RequestMapping(value = "/student/practice-improve/{fieldId}/{knowledgePointId}/{questionTypeId}/{isShuffle}", method = RequestMethod.GET)
	public String practiceImprove(Model model, HttpServletRequest request, @PathVariable("fieldId") int fieldId,
			@PathVariable("knowledgePointId") int knowledgePointId, @PathVariable("questionTypeId") int questionTypeId,
			@PathVariable("isShuffle") int isShuffle) {
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

		String strUrl = "http://" + request.getServerName() // 服务器地址
				+ ":" + request.getServerPort() + "/";
		List<QuestionQueryResult> qqrList = questionMapper.getQuestionListByFieldIdQTypeId(fieldId, questionTypeId, null);//questionService.getQuestionByFieldId(fieldId);//questionService.getQuestionAnalysisListByPointIdAndTypeId(questionTypeId, knowledgePointId);
		List<QuestionQueryResult> qqrList0 = questionMapper.getQuestionListByFieldId(fieldId, null);
		if (qqrList.size() > 0 && isShuffle == 1)
			Collections.shuffle(qqrList); // 随机试题顺序

		String questionTypeName = "";
		String fieldName = "";
		try {
			fieldName = qqrList.get(0).getPointName().split(">")[1];
		} catch (Exception e) {
			// log.info(e.getMessage());
		}

		Map<Integer, QuestionType> questionTypeMap = questionService.getQuestionTypeMap();
		for (Map.Entry<Integer, QuestionType> entry : questionTypeMap.entrySet()) {

			if (entry.getKey() == questionTypeId) {
				questionTypeName = entry.getValue().getName();
				break;
			}
		}
		int amount = qqrList0.size();
		StringBuilder sb = new StringBuilder();
		for (QuestionQueryResult qqr : qqrList) {
			QuestionAdapter adapter = new QuestionAdapter(qqr, strUrl);
			sb.append(adapter.getStringFromXML(false, false));
		}

		/**
		 * 试题类型
		 */
		// 试题数量
		Map<Integer, Map<Integer, QuestionStatistic>> questionMap = questionService
				.getTypeQuestionStaticByFieldId(fieldId);
		// 练习历史试题数量
		Map<Integer, Map<Integer, QuestionStatistic>> historyMap = questionHistoryService
				.getTypeQuestionHistStaticByFieldId(fieldId, userInfo.getUserid());
		// 练习历史试题数量（历史错题）

		// 题库下的知识点
		Map<Integer, KnowledgePoint> pointMap = questionService.getKnowledgePointByFieldId(null, fieldId);
		
		List<UserQuestionHistory> histList = questionHistoryMapper.getUserQuestionHist(userInfo.getUserid(), fieldId);
		String hisStr = "";
		for(UserQuestionHistory uqh :histList) {
			hisStr+=uqh.getQuestionId()+",";
		}
		
		List<KnowledgePointAnalysisResult> kparl = new ArrayList<KnowledgePointAnalysisResult>();
		for (Map.Entry<Integer, Map<Integer, QuestionStatistic>> entry : questionMap.entrySet()) {
			KnowledgePointAnalysisResult kpar = new KnowledgePointAnalysisResult();
			kpar.setKnowledgePointId(entry.getKey());
			List<TypeAnalysis> tal = new ArrayList<TypeAnalysis>();
			int totalRightAmount = 0;
			int totalAmount = 0;
			for (Map.Entry<Integer, QuestionStatistic> entry1 : entry.getValue().entrySet()) {
				TypeAnalysis ta = new TypeAnalysis();
				ta.setQuestionTypeId(entry1.getKey());
				ta.setQuestionTypeName(entry1.getValue().getQuestionTypeName());
				int rightAmount = 0;
				int wrongAmount = 0;
				try {
					rightAmount = historyMap.get(entry.getKey()).get(entry1.getKey()).getRightAmount();
				} catch (Exception e) {
				}
				try {
					wrongAmount = historyMap.get(entry.getKey()).get(entry1.getKey()).getWrongAmount();
				} catch (Exception e) {
				}
				ta.setRightAmount(rightAmount);
				ta.setWrongAmount(wrongAmount);
				ta.setRestAmount(entry1.getValue().getAmount() - rightAmount - wrongAmount);
				tal.add(ta);
				if (kpar.getKnowledgePointName() == null)
					kpar.setKnowledgePointName(entry1.getValue().getPointName());
				totalRightAmount += rightAmount;
				totalAmount += entry1.getValue().getAmount();
			}
			kpar.setTypeAnalysis(tal);
			if (totalAmount > 0)
				kpar.setFinishRate((float) totalRightAmount / (float) totalAmount);
			kparl.add(kpar);
		}
		model.addAttribute("kparl", kparl);
		model.addAttribute("questionStr", sb.toString());
		model.addAttribute("amount", amount);
		model.addAttribute("questionTypeName", questionTypeName);
		model.addAttribute("practiceName", "初阶训练");
		model.addAttribute("knowledgePointId", knowledgePointId);
		model.addAttribute("questionTypeId", questionTypeId);
		model.addAttribute("fieldId", fieldId);
		model.addAttribute("questionHisStr",hisStr);
		return "practice-improve-qh";
	}

	/**
	 * 错题练习
	 * 
	 * @param model
	 * @param exam_history_id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/student/practice-incorrect/{fieldId}/{knowledgePointId}/{isShuffle}", method = RequestMethod.GET)
	public String practiceCollectQuestions(Model model, HttpServletRequest request,
			@PathVariable("fieldId") int fieldId, @PathVariable("knowledgePointId") int knowledgePointId,
			@PathVariable("isShuffle") int isShuffle) {

		String strUrl = "http://" + request.getServerName() // 服务器地址
				+ ":" + request.getServerPort() + "/";
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		// 历史
		Map<Integer, List<UserQuestionHistory>> historyMap = questionHistoryService
				.getUserQuestionHist(userInfo.getUserid(), fieldId);
		List<UserQuestionHistory> histList = questionHistoryMapper.getUserQuestionHist(userInfo.getUserid(), fieldId);
		
		List<UserQuestionHistory> historyList = historyMap.get(knowledgePointId);
		
		historyList = histList;
		// 收藏
		Map<Integer, List<UserQuestionCollect>> collectsMap = questionCollectService
				.getUserQuestionCollect(userInfo.getUserid(), fieldId);

		List<UserQuestionCollect> collects = collectsMap.get(knowledgePointId);

		List<Integer> idList = new ArrayList<Integer>();

		if(historyList!=null && historyList.size()>0){
			for (UserQuestionHistory history : historyList) {
				if (!history.isRight())
					idList.add(history.getQuestionId());
			}
		}

		List<QuestionQueryResult> qqrList = new ArrayList<QuestionQueryResult>();
		if (idList.size() > 0)
			qqrList = questionService.getQuestionAnalysisListByIdList(idList);
		if (qqrList.size() > 0 && isShuffle == 1)
			Collections.shuffle(qqrList); // 随机试题顺序

		int amount = idList.size();
		StringBuilder sb = new StringBuilder();
		for (QuestionQueryResult qqr : qqrList) {
			QuestionAdapter adapter = new QuestionAdapter(qqr, strUrl);
			sb.append(adapter.getStringFromXMLErr(false,false,true, true));
		}

		model.addAttribute("questionStr", sb.toString());
		model.addAttribute("amount", amount);
		model.addAttribute("questionTypeName", "错题集中营");
		model.addAttribute("practiceName", "错题集中营（连续答对3次方可出库）");
		return "practice-improve";
	}

	/**
	 * 收藏练习
	 * 
	 * @param model
	 * @param exam_history_id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/student/practice-collect/{fieldId}/{knowledgePointId}/{isShuffle}", method = RequestMethod.GET)
	public String practiceIncorrectQuestions(Model model, HttpServletRequest request,
			@PathVariable("fieldId") int fieldId, @PathVariable("knowledgePointId") int knowledgePointId,
			@PathVariable("isShuffle") int isShuffle) {

		String strUrl = "http://" + request.getServerName() // 服务器地址
				+ ":" + request.getServerPort() + "/";
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		// 收藏
		Map<Integer, List<UserQuestionCollect>> collectsMap = questionCollectService
				.getUserQuestionCollect(userInfo.getUserid(), fieldId);

		List<UserQuestionCollect> collects = collectsMap.get(knowledgePointId);

		List<Integer> idList = new ArrayList<Integer>();

		for (UserQuestionCollect co : collects) {
			if (!co.isCollect())
				idList.add(co.getQuestionId());
		}

		List<QuestionQueryResult> qqrList = new ArrayList<QuestionQueryResult>();
		if (idList.size() > 0)
			qqrList = questionService.getQuestionAnalysisListByIdList(idList);
		if (qqrList.size() > 0 && isShuffle == 1)
			Collections.shuffle(qqrList); // 随机试题顺序

		int amount = idList.size();
		StringBuilder sb = new StringBuilder();
		for (QuestionQueryResult qqr : qqrList) {
			QuestionAdapter adapter = new QuestionAdapter(qqr, strUrl);
			sb.append(adapter.getStringFromXML(true, false));
		}

		model.addAttribute("questionStr", sb.toString());
		model.addAttribute("amount", amount);
		model.addAttribute("questionTypeName", "收藏库");
		model.addAttribute("practiceName", "收藏练习");
		return "practice-improve";
	}

	/**
	 * 获取用户的练习记录（试题ID）
	 * 
	 * @param userId
	 * @param knowledgePointId
	 * @return
	 */
	@RequestMapping(value = "/student/practice-improve-his/{fieldId}/{knowledgePointId}/{questionTypeId}", method = RequestMethod.GET)
	public @ResponseBody List<Integer> getFinishedQuestionId(Model model, HttpServletRequest request,
			@PathVariable("fieldId") int fieldId, @PathVariable("knowledgePointId") int knowledgePointId,
			@PathVariable("questionTypeId") int questionTypeId) {

		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		/*Map<Integer, List<UserQuestionHistory>> historyMap = questionHistoryService
				.getUserQuestionHist(userInfo.getUserid(), fieldId);*/
		List<UserQuestionHistory> historylists= questionHistoryMapper.getUserQuestionHist(userInfo.getUserid(), fieldId);
		List<Integer> l = new ArrayList<Integer>();
		for(UserQuestionHistory uqh : historylists) {
			l.add(uqh.getQuestionId());
		}

		return l;

	}

	@RequestMapping(value = "/student/practice-test/{fieldId}/{num}", method = RequestMethod.GET)
	public String practiceStartNew(Model model, HttpServletRequest request, @PathVariable("fieldId") int fieldId,
			@PathVariable("num") int num) {

		String strUrl = "http://" + request.getServerName() // 服务器地址
				+ ":" + request.getServerPort() + "/";

		Map<Integer, Map<Integer, List<QuestionQueryResult>>> map = questionService.getQuestionMapByFieldId(fieldId,
				null);
		List<QuestionQueryResult> qqrList = new ArrayList<QuestionQueryResult>();
		for (Map.Entry<Integer, Map<Integer, List<QuestionQueryResult>>> entry : map.entrySet()) {
			for(int i=0; i<100;i++){
				if (entry.getValue().containsKey(i))
					qqrList.addAll(entry.getValue().get(i));
			}
		}
		int amount = 0;
		if (qqrList.size() == 0) {
			model.addAttribute("errorMsg", "无可用的题目");
			return "error";
		}

		StringBuilder sb = new StringBuilder();
		Random random = new Random();

		num = num == 0 ? qqrList.size() : num;

		/*
		 * for(int i = 0 ; i < num ; i ++){ int questionCount = qqrList.size();
		 * int index = random.nextInt(questionCount); QuestionAdapter adapter =
		 * new QuestionAdapter(qqrList.get(i),strUrl);//new
		 * QuestionAdapter(qqrList.get(index),strUrl);
		 * sb.append(adapter.getStringFromXML(false)); qqrList.remove(index);
		 * amount ++; if(qqrList.size() == 0) break; }
		 */
		for (QuestionQueryResult qqr : qqrList) {
			QuestionAdapter adapter = new QuestionAdapter(qqr, strUrl);
			sb.append(adapter.getStringFromXML(false, false, false, true));//getStringFromXML(false));
			amount++;
		}
		model.addAttribute("questionStr", sb.toString());
		model.addAttribute("amount", amount);
		model.addAttribute("questionTypeName", "试题初记");
		model.addAttribute("practiceName", "试题初记");
		return "practice-improve-test";
	}

	/**
	 * 苦思冥想模式
	 * 
	 * @param model
	 * @param request
	 * @param fieldId
	 * @param num
	 * @return
	 */
	@RequestMapping(value = "/student/practice-ksmx/{fieldId}/{num}/{isShuffle}", method = RequestMethod.GET)
	public String practiceKsmx(Model model, HttpServletRequest request, @PathVariable("fieldId") int fieldId,
			@PathVariable("num") int num, @PathVariable("isShuffle") int isShuffle) {

		String strUrl = "http://" + request.getServerName() // 服务器地址
				+ ":" + request.getServerPort() + "/";

		Map<Integer, Map<Integer, List<QuestionQueryResult>>> map = questionService.getQuestionMapByFieldId(fieldId,
				null);
		List<QuestionQueryResult> qqrList = new ArrayList<QuestionQueryResult>();
		for (Map.Entry<Integer, Map<Integer, List<QuestionQueryResult>>> entry : map.entrySet()) {
			if (entry.getValue().containsKey(1))
				qqrList.addAll(entry.getValue().get(1));
			if (entry.getValue().containsKey(2))
				qqrList.addAll(entry.getValue().get(2));
			/*if (entry.getValue().containsKey(3))
				qqrList.addAll(entry.getValue().get(3));*/
		}
		int amount = 0;                       
		if (qqrList.size() == 0) {
			model.addAttribute("errorMsg", "无可用的题目");
			return "error";
		}

		StringBuilder sb = new StringBuilder();
		Random random = new Random();

		num = num == 0 ? qqrList.size() : num;
		if (isShuffle == 0) {
			for (QuestionQueryResult qqr : qqrList) {
				QuestionAdapter adapter = new QuestionAdapter(qqr, strUrl);
				sb.append(adapter.getStringFromXML(false,true));
				amount++;
			}
		} else {
			// 随机出题算法
			for (int i = 0; i < num; i++) {
				int questionCount = qqrList.size();
				int index = random.nextInt(questionCount);
				QuestionAdapter adapter = new QuestionAdapter(qqrList.get(index), strUrl);
				sb.append(adapter.getStringFromXML(false, true));
				qqrList.remove(index);
				amount++;
				if (qqrList.size() == 0)
					break;
			}
		}

		model.addAttribute("questionStr", sb.toString());
		model.addAttribute("amount", amount);
		model.addAttribute("questionTypeName", "苦思冥想");
		model.addAttribute("practiceName", "苦思冥想");
		return "practice-improve-ksmx";
	}

	@RequestMapping(value = "/student/practice-list", method = RequestMethod.GET)
	public String practiceListPage(Model model, HttpServletRequest request,
			@RequestParam(value = "fieldId", required = false, defaultValue = "0") int fieldId) {

		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

		Page<News> pageModel = new Page<News>();
		pageModel.setPageNo(1);
		pageModel.setPageSize(2);
		List<News> newsList = newsService.getNewsList(pageModel);
		model.addAttribute("newsList", newsList);

		request.getSession().removeAttribute("SPRING_SECURITY_LAST_EXCEPTION");
		String result = request.getParameter("result");
		if ("failed".equals(result)) {
			model.addAttribute("result_msg", "登陆失败");
		}

		if (SecurityContextHolder.getContext().getAuthentication() == null) {
			// this.appendBaseInfo(model);
			return "practice";
		}
		if (SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()
				.endsWith("anonymousUser")) {
			// this.appendBaseInfo(model);
			return "practice";
		}

		// 非常关键，只有histid被重置，其他都不变
		if (userInfo.getHistId() != 0) {
			return "redirect:student/exam-start/" + userInfo.getExamId();
		}

		// 题库列表
		List<Field> fieldList = questionService.getAllField(null);
		if (fieldId == 0)
			fieldId = fieldList.get(0).getFieldId();

		fieldId = Integer.parseInt(request.getSession().getAttribute("fieldId").toString());
		// 试题数量
		Map<Integer, Map<Integer, QuestionStatistic>> questionMap = questionService
				.getTypeQuestionStaticByFieldId(fieldId);
		// 练习历史试题数量
		Map<Integer, Map<Integer, QuestionStatistic>> historyMap = questionHistoryService
				.getTypeQuestionHistStaticByFieldId(fieldId, userInfo.getUserid());
		// 练习历史试题数量（历史错题）
		Map<Integer, QuestionStatistic> historyStatisticMap = questionHistoryService
				.getQuestionHistStaticByFieldId(fieldId, userInfo.getUserid());
		// 收藏的题目
		Map<Integer, Map<Integer, QuestionStatistic>> collectMap = questionCollectService
				.getTypeQuestionCollectStaticByFieldId(fieldId, userInfo.getUserid());
		Map<Integer, QuestionStatistic> collectsMap = questionCollectService.getQuestionCollectStaticByFieldId(fieldId,
				userInfo.getUserid());

		// 题库下的知识点
		Map<Integer, KnowledgePoint> pointMap = questionService.getKnowledgePointByFieldId(null, fieldId);

		List<KnowledgePointAnalysisResult> kparl = new ArrayList<KnowledgePointAnalysisResult>();
		for (Map.Entry<Integer, Map<Integer, QuestionStatistic>> entry : questionMap.entrySet()) {
			KnowledgePointAnalysisResult kpar = new KnowledgePointAnalysisResult();
			kpar.setKnowledgePointId(entry.getKey());
			List<TypeAnalysis> tal = new ArrayList<TypeAnalysis>();
			int totalRightAmount = 0;
			int totalAmount = 0;
			for (Map.Entry<Integer, QuestionStatistic> entry1 : entry.getValue().entrySet()) {
				TypeAnalysis ta = new TypeAnalysis();
				ta.setQuestionTypeId(entry1.getKey());
				ta.setQuestionTypeName(entry1.getValue().getQuestionTypeName());
				int rightAmount = 0;
				int wrongAmount = 0;
				try {
					rightAmount = historyMap.get(entry.getKey()).get(entry1.getKey()).getRightAmount();
					wrongAmount = historyMap.get(entry.getKey()).get(entry1.getKey()).getWrongAmount();
				} catch (Exception e) {
				}
				ta.setRightAmount(rightAmount);
				ta.setWrongAmount(wrongAmount);
				ta.setRestAmount(entry1.getValue().getAmount() - rightAmount - wrongAmount);
				tal.add(ta);
				if (kpar.getKnowledgePointName() == null)
					kpar.setKnowledgePointName(entry1.getValue().getPointName());
				totalRightAmount += rightAmount;
				totalAmount += entry1.getValue().getAmount();
			}
			kpar.setTypeAnalysis(tal);
			if (totalAmount > 0)
				kpar.setFinishRate((float) totalRightAmount / (float) totalAmount);
			kparl.add(kpar);
		}

		model.addAttribute("kparl", kparl);
		model.addAttribute("fieldId", fieldId);
		model.addAttribute("historyMap", historyStatisticMap);

		model.addAttribute("collectMap", collectsMap);
		model.addAttribute("pointMap", pointMap);
		model.addAttribute("fieldList", fieldList);
		return "practice";
	}

	/*
	 * public void appendBaseInfo(Model model,int fieldId){
	 * 
	 * Object userInfo = SecurityContextHolder.getContext() .getAuthentication()
	 * .getPrincipal();
	 * 
	 * if(!(userInfo instanceof String)){
	 * 
	 * Map<Integer,List<UserQuestionHistory>> histMap =
	 * questionHistoryService.getUserQuestionHist(((UserInfo)userInfo).getUserid
	 * (), fieldId);
	 * 
	 * Map<Integer,KnowledgePoint> pointMap =
	 * questionService.getKnowledgePointByFieldId(fieldId,null);
	 * Map<Integer,QuestionType> typeMap = questionService.getQuestionTypeMap();
	 * int wrongCount = 0; for(Map.Entry<Integer,List<UserQuestionHistory>>
	 * entry : histMap.entrySet()){ wrongCount += entry.getValue().size();
	 * 
	 * }
	 * 
	 * //获取每个知识点已做题数目 Map<Integer,Map<Integer,Integer>> doneNumMap = new
	 * HashMap<Integer,Map<Integer,Integer>>();
	 * for(Map.Entry<Integer,List<UserQuestionHistory>> entry :
	 * histMap.entrySet()){ Map<Integer,Integer> tmp =
	 * doneNumMap.get(entry.getKey()); if(tmp == null) tmp = new
	 * HashMap<Integer,Integer>();
	 * 
	 * for(UserQuestionHistory history : entry.getValue()){ int count = 1; count
	 * += !tmp.containsKey(history.getQuestionTypeId()) ? 0 :
	 * tmp.get(history.getQuestionTypeId());
	 * tmp.put(history.getQuestionTypeId(), count); }
	 * doneNumMap.put(entry.getKey(), tmp); }
	 * 
	 * Map<Integer, Map<Integer,List<QuestionQueryResult>>> questionMap =
	 * questionService.getQuestionMapByFieldId(fieldId, null);
	 * model.addAttribute("histMap", histMap); model.addAttribute("wrongCount",
	 * wrongCount); model.addAttribute("pointMap", pointMap);
	 * model.addAttribute("typeMap", typeMap); model.addAttribute("questionMap",
	 * questionMap); model.addAttribute("doneNumMap", doneNumMap);
	 * model.addAttribute("fieldId", fieldId); } }
	 */
}
